package com.engine.cese.duss.invoice.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.cese.duss.invoice.util.OcrUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.interfaces.cese.duss.ceseutil.CostUtil;
import weaver.interfaces.cese.duss.ceseutil.ImageUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2021-03-10
 * @Description: ${description}
 * @ModifyLog:
 **/

public class WeaInvoiceVerifiedAction {

    /**
     *@Description: ORC发票识别
     *@Param: [request, response]
     *@return: java.lang.String
     *@Author: Dusongsong
     *@Date: 2021/3/10
     */
    @GET
    @Path("/getImageRecognition")
    @Produces({MediaType.TEXT_PLAIN})
    public String getImageRecognition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        BaseBean baseBean = new BaseBean();
        try {
            User user = HrmUserVarify.getUser( request, response );
            int userid = user.getUID();//获取当前登录人员
            Map<String, String> returnMap = OcrUtil.getDepartAndSub( userid + "" );
            String department = returnMap.get( "departmentid" );//部门
            String supsubcom = returnMap.get( "subcompanyid1" );//分部
            String currentDate = DateUtil.getCurrentDate();//当前日期
            //浪潮影像识别接口
            String YX_API_KEY = baseBean.getPropValue( "langchao", "YX_API_KEY" );
            String yx_url = baseBean.getPropValue( "langchao", "yx_url" );
            String yx_cut_url = baseBean.getPropValue( "langchao", "yx_cut_url" );
            String fileIds = Util.null2String( request.getParameter( "fileIds" ) );//文件ID
            String msg = "";//返回信息
            int sumCount = 0;//发票总数
            int failedCount = 0;//识别失败记数
            int successCount = 0;//识别成功记数
            int isRepCount = 0;//识别重复记数
            String[] arr = fileIds.split( "," );
            for (int i=0;i<arr.length;i++) {
                int oldFileId = Util.getIntValue(arr[i]);
                baseBean.writeLog( "--------------getImageRecognition--------------oldFileId=" + oldFileId );
                //插入影像表
                boolean yxbz = OcrUtil.insertImageInfo( userid, oldFileId, currentDate );
                String newFileIds = ImageUtil.imageCut( userid, oldFileId, yx_cut_url, YX_API_KEY );
                newFileIds = "".equals(newFileIds)?oldFileId+"":newFileIds;
                String[] newArr = newFileIds.split( "," );
                for (int j=0;j<newArr.length;j++) {
                    sumCount++;
                    int fileId = Util.getIntValue(newArr[j]);
                    baseBean.writeLog( "--------------getImageRecognition--------------fileId" + fileId );
                    String result = OcrUtil.sendPostHttpOCR( yx_url, fileId, YX_API_KEY );
                    baseBean.writeLog( "发票识别接口返回：" + result );
                    JSONObject resultJson = JSONObject.parseObject( result );
                    //发票识别
                    if (!"".equals( result )) {
                        String formmodeid = CostUtil.getFormmodeId( "uf_fpxx" );
                        JSONObject response1 = JSONObject.parseObject( resultJson.getString( "response" ) );
                        JSONObject data = JSONObject.parseObject( response1.getString( "data" ) );
                        JSONArray identifyResults = JSONArray.parseArray( data.getString( "identifyResults" ) );
                        for (int k = 0; k < identifyResults.size(); k++) {
                            JSONObject results = (JSONObject) identifyResults.get( k);
                            String category = results.getString( "category" );//发票类型
                            JSONObject details = JSONObject.parseObject( results.getString( "details" ) );//发票识别的具体信息
                            baseBean.writeLog( "=================category=" + category );
                            boolean flag;
                            switch (category) {
                                case "vat":
                                    flag = OcrUtil.getTicketType_var( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "vat_roll":
                                    flag = OcrUtil.getTicketType_var( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "machine_invoice":
                                    flag = OcrUtil.getTicketType_machine_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "vehicle_invoice":
                                    flag = OcrUtil.getTicketType_vehicle_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "air_ticket":
                                    flag = OcrUtil.getTicketType_air_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "taxi_ticket":
                                    flag = OcrUtil.getTicketType_taxi_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "train_ticket":
                                    flag = OcrUtil.getTicketType_train_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "pass_ticket":
                                    flag = OcrUtil.getTicketType_pass_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "bus_ticket":
                                    flag = OcrUtil.getTicketType_bus_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "small_ticket":
                                    flag = OcrUtil.getTicketType_small_ticket( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "quota_invoice":
                                    flag = OcrUtil.getTicketType_quota_invoice( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                                case "others":
                                    flag = OcrUtil.getTicketType_others( userid, currentDate, supsubcom, department, fileId, formmodeid, category, details );
                                    if (flag) {
                                        successCount++;
                                    }else {
                                        isRepCount++;
                                    }
                                    if (yxbz) {
                                        OcrUtil.updateImageInfo( userid, fileId, currentDate );
                                    }
                                    break;
                            }
                        }
                    } else {
                        failedCount++;
                    }
                }
            }
            msg =  "发票识别结果：[识别总数:" + sumCount + "张]；[识别成功:" + successCount + "张]；" +
                    "[识别失败:" + failedCount + "张]；[识别重复:" + isRepCount + "张]";
            apidatas.put( "msg", msg );
            apidatas.put( "api_status", true );
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put( "api_status", false );
            apidatas.put( "error_message", "请求异常" );
        }
        return JSONObject.toJSONString( apidatas );
    }
    /**
     *@Description: 发票验真
     *@Param: [request, response]
     *@return: java.lang.String
     *@Author: Dusongsong
     *@Date: 2021/3/10
     */
    @GET
    @Path("/getInvoiceVerified")
    @Produces({MediaType.TEXT_PLAIN})
    public String getInvoiceVerified(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        BaseBean baseBean = new BaseBean();
        try {
            String ids = Util.null2String( request.getParameter( "ids" ) );//文件ID
            boolean flag = true;
            String msg = "";
            RecordSet rs = new RecordSet();
            String sql = "select fplx,fpzw,fpdm,fphm,fprq,bhsje,checkCode,sellerRegisterNum,gmfmc from uf_fpxx where id in (" + ids + ")";
            rs.executeQuery( sql );
            while (rs.next()) {
                String fpzw = Util.null2String( rs.getString( "fpzw" ) );
                String fplx = Util.null2String( rs.getString( "fplx" ) );
                String fpdm = Util.null2String( rs.getString( "fpdm" ) );
                String fphm = Util.null2String( rs.getString( "fphm" ) );
                String fprq = Util.null2String( rs.getString( "fprq" ) );
                String bhsje = Util.null2String( rs.getString( "bhsje" ) );
                String checkCode = Util.null2String( rs.getString( "checkCode" ) );
                String purchaserName = Util.null2String( rs.getString( "gmfmc" ) );
                String sellerRegisterNum = Util.null2String( rs.getString( "sellerRegisterNum" ) );//预留电话
                baseBean.writeLog( String.join( "-", fplx, fpdm, fphm, fprq, bhsje, checkCode, sellerRegisterNum ) );
                if("0".equals( fplx ) ||"1".equals( fplx ) ||"11".equals( fplx )||"14".equals( fplx )||"15".equals( fplx )){
                    if ("1".equals( fpzw ) || "2".equals( fpzw )) {
                        Map<String,Object> resultMap = OcrUtil.invoicerecertify( fplx, fpdm, fphm, fprq, bhsje, checkCode, sellerRegisterNum,purchaserName );
                        flag = (boolean) resultMap.get("flag");
                        msg = (String) resultMap.get("msg");
                    }  else if ("0".equals( fpzw )) {
                        flag = false;
                        msg = "系统提示：发票已经验真通过";
                    }else {
                        flag = false;
                        msg = "系统提示：只有[认证不通过]的发票才能重新验真";
                    }
                }else {
                    flag = false;
                    msg = "系统提示：此发票不能验真";
                }
            }
            apidatas.put( "msg", msg );
            apidatas.put( "flag", flag );
            apidatas.put( "api_status", true );
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put( "api_status", false );
            apidatas.put( "error_message", "请求异常" );
        }
        return JSONObject.toJSONString( apidatas );
    }
}
